package org.example.sdk;

import java.io.IOException;
import java.util.Iterator;

class ResourceIterator<T> implements Iterator<T> {

    private final ResourceFetcher<T> fetcher;
    private ListResult<T> res;
    private int pos;
    private boolean hasNext;

    public ResourceIterator(ResourceFetcher<T> fetcher) {
        this.fetcher = fetcher;
    }

    private void fill() throws IOException {
        if (res == null) {
            res = fetcher.fetch(null);
            pos = 0;
            hasNext = !res.getList().isEmpty();
        } else if (pos >= res.getList().size()) {
            if (res.getNextToken() != null) {
                res = fetcher.fetch(res.getNextToken());
                pos = 0;
                hasNext = !res.getList().isEmpty();
            } else {
                hasNext = false;
            }
        }
    }

    @Override
    public boolean hasNext() {
        try {
            fill();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return hasNext;
    }

    @Override
    public T next() {
        return res.getList().get(pos++);
    }
}
